package com.lzh.seatrend.util.seatrend;

import com.lzh.seatrend.config.datasource.BaseConfig;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
//jdk提供的标准字符编码
import java.nio.charset.StandardCharsets;

/**
 * AES加密
 */
public class AesUtil {

    private static final int NUMBER_TWO = 2;
    private static final int NUMBER_SIXTEEN = 16;
    /**
     * 密匙算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加密解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";

    private static byte[] operation(byte[] src, String key, int mode) throws Exception {
        if ( key == null ){
            System.out.println("Key不能为空");
            return null;
        }
        if ( key.length() != NUMBER_SIXTEEN){
            System.out.println("Key需要16位长度");
            return null;
        }
        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        //SecretKeySpec类是KeySpec接口的实现类,用于构建秘密密钥规范
        SecretKeySpec keySpec = new SecretKeySpec(raw,ALGORITHM);
        //创建密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        //初始化
        cipher.init(mode,keySpec);
        byte[] encrypted = cipher.doFinal(src);
        return encrypted;
    }

    public static String encrypt(String content, String key) throws Exception{
        byte[] src = content.getBytes(StandardCharsets.UTF_8);
        byte[] result = operation(src, key, Cipher.ENCRYPT_MODE);
        return toHexString(result);
    }

    public static String decrypt(String content, String key) throws Exception{
        byte[] src = toBytes(content);
        byte[] result = operation(src, key, Cipher.DECRYPT_MODE);
        return new String(result);
    }
    
    public static byte[] toBytes(String str){
        if (str == null || "".equals(str.trim())){
            return new byte[0];
        }
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / NUMBER_TWO; i++) {
            String substring = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(substring,16);
        }
        return bytes;
    }

    public static String toHexString(byte[] b){
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if ( plainText.length() < 2 ){
                plainText = "0" + plainText;
            }
            hexString.append(plainText);
        }
        return hexString.toString().toUpperCase();
    }

    public static void main(String[] args) throws Exception {
        String encrypt = AesUtil.encrypt(
                "jdbc:mysql://127.0.0.1:3306/cloud_user?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8",
                BaseConfig.ENCRYPT_KEY);
        System.out.println(encrypt);
    }
}

